package per.dg.keepalive.multiprocess.aidl

import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log

class GuardProcessServerService : Service() {

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startAndBindGuardProcessClientService()
        return START_STICKY
    }

    override fun onBind(intent: Intent): IBinder {
        return IGuardProcessServerInterfaceStub()
    }

    private fun startAndBindGuardProcessClientService(){
        var intent = Intent(this, GuardProcessClientService::class.java)
        startService(intent)
        bindService(intent, mServiceConnection, Service.BIND_IMPORTANT)
    }

    private val mServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            Log.e("onServiceDisconnected: ", "连接断开，重新启动客户端 service")
            startAndBindGuardProcessClientService()
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            var mIGuardProcessServerInterface : IGuardProcessInterface = IGuardProcessInterface.Stub.asInterface(service)
            Log.e("onServiceConnected: ", "连接到客户端 service，客户端 service 名称"+mIGuardProcessServerInterface.serviceName)
        }
    }

    private inner class IGuardProcessServerInterfaceStub : IGuardProcessInterface.Stub(){
        override fun getServiceName() : String {
            return GuardProcessServerService::class.java.name
        }
    }
}